<?php

namespace app\common;

use app\model\ActivityMall;
use app\tool\Http;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
use think\Exception;
use think\facade\Log;
use think\helper\Str;
use think\Response;

class Activity
{
	
	static function mall()
	{
		return [
			['name' => 'HKTVmall', 'url' => 'hktvmall.com'],
			['name' => 'Openrice', 'url' => 'openrice.com'],
			['name' => 'Price', 'url' => 'price.com'],
			['name' => '屈臣氏', 'url' => 'watsons.com'],
			['name' => 'Sasa eShop', 'url' => 'hk17.page.link'],
			['name' => 'ZALORA', 'url' => 'zalora.com'],
			['name' => 'Klook', 'url' => 'klook.com'],
			['name' => 'Ztore', 'url' => 'ztore.com'],
			['name' => 'PNS', 'url' => 'pns.hk'],
			['name' => 'IKEA HK', 'url' => 'ikea.com'],
			['name' => 'Iherb', 'url' => 'iherb.com'],
			['name' => 'Mydress', 'url' => 'hk20.page.link'],
			['name' => 'Trip', 'url' => 'trip.com'],
			['name' => 'Carousell', 'url' => 'carousell.app.link'],
		];
	}
	
	/**
	 * 解析口令链接
	 * @param $short_link
	 * @return array|false|void
	 */
	static function unpack($short_link)
	{
		preg_match('/(http|https|ftp)(.)*([a-z0-9\-._])+/i', $short_link, $result);
		$name = '';
		$mall_id = 15;//其他平台
		if (is_array($result) && !empty($result)) {
			$A = urldecode($result[0]);
			$mall = ActivityMall::select();
			foreach ($mall as $v) {
				if (Str::contains($A, $v['url'])) {
					$name = $v['name'];
					$mall_id = $v['id'];
					break;
				}
			}
		} else {
			throw new Exception('解析链接失败');
		}
		
		$goods_pd = get_uniqid();
		$price = 0;
		$images = '';
		$title = '';
		$detail = '';
		$history = true;
		
		switch ($name) {
			case 'HKTVmall':
				$content = http_request($A);
				$start_con = stripos($content, 'var productData =');
				$end_con = stripos($content, '};', $start_con + 1);
				$res = substr($content, $start_con, $end_con - $start_con);
				$json_info = str_replace('var productData =', '', $res) . '}';
				$json_info = json_decode($json_info);
				$detail = $json_info->description;
				$price_value = null;
				foreach ($json_info->priceList as $v) {
					if ($v->priceType == 'DISCOUNT') {
						$price_value = $v->value;
					}
				}
				if (!$price_value) {
					$price_value = $json_info->priceList[0]->value;
				}
				$price = round($price_value, 2);
				$images = implode(',', $json_info->imageUrls);
				$brandName = $json_info->brandName ? $json_info->brandName . '-' : '';
				$title = $brandName . $json_info->name;
				$goods_pd = $json_info->code;
				break;
			case '携程旅行':
				$A = get_redirect_url($A);
				$content = Http::get($A);
				$start = stripos($content, '<script type="application/ld+json">');
				$end = stripos($content, '</script>', $start + 1);
				$res = substr($content, $start, $end - $start);
				$json_info = str_replace('<script type="application/ld+json">', '', $res);
				$json_info = htmlspecialchars_decode($json_info);
				$json_info = json_decode($json_info);
				$title = $json_info->name;
				$hashotelid = stripos($A, 'hotelid=');
				if ($hashotelid !== false) {
					$detail = $json_info->priceRange;
					$images = $json_info->image;
					$start = stripos($A, 'hotelid=');
					$end = stripos($A, '&', $start + 1);
					$res = substr($A, $start, $end - $start);
					$goods_pd = str_replace('hotelid=', '', $res);
				} else {
					$start = stripos($A, 'detail/');
					$end = stripos($A, '?', $start + 1);
					$res = substr($A, $start, $end - $start);
					$goods_pd = str_replace('detail/', '', $res);
					$detail = $json_info->description;
					$images = implode(',', $json_info->image);
				}
				break;
			case 'OpenRice':
				$content = http_request($A);
				$start = stripos($content, '<script>window.__INITIAL_STATE__=');
				$end = stripos($content, '</script>', $start + 1);
				$res = substr($content, $start, $end - $start);
				$start = stripos($res, '<script>window.__INITIAL_STATE__=');
				$end = strrpos($res, '};');
				$res = substr($res, $start, $end - $start);
				$json_info = str_replace('<script>window.__INITIAL_STATE__=', '', $res) . '}';
				$json = json_decode($json_info);
				$start = stripos($content, '<div class="door-photo" style="background-image:url(');
				$end = stripos($content, ')', $start + 1);
				$images = str_replace('<div class="door-photo" style="background-image:url(', '', substr($content, $start, $end - $start));
				$detail = $json->offer->offerDetail->coupon->desc;
				$price = $json->offer->offerDetail->coupon->tmOfferDetail->discountPrice;
				$title = $json->offer->offerDetail->coupon->title;
				$start = strrpos($A, '/');
				$goods_pd = trim(strip_tags(substr($A, $start + 1)));
				break;
			case 'Price':
				$content = Http::get($A);
				$start = stripos($content, '<div class="outlet-product-image">');
				$end = stripos($content, '</div>', $start + 1);
				$res = substr($content, $start, $end - $start);
				preg_match_all('/<a href="/', $res, $images, PREG_OFFSET_CAPTURE);//图片
				$image_url = [];
				foreach ($images[0] as $v) {
					$start = $v[1];
					$end = stripos($res, '"', $start + 15);
					$ooo = substr($res, $start, $end - $start);
					$image_url[] = 'https://www.price.com.hk' . str_replace('<a href="', '', $ooo);
				}
				$images = implode(',', $image_url);
				$start = stripos($content, '<h4 class="detail-pdname">');
				$end = stripos($content, '</h4>', $start + 1);
				$res = substr($content, $start, $end - $start);
				$title = trim(strip_tags(str_replace('<h4 class="detail-pdname">', '', $res)));
				$start = strrpos($A, 'ecpid=');
				$goods_pd = str_replace('ecpid=', '', substr($A, $start));
				$start = stripos($content, '<dd class="oul-product-discounted-price info-form-content">');
				$end = stripos($content, '</dd>', $start + 1);
				$res = str_replace('<dd class="oul-product-discounted-price info-form-content">', '', substr($content, $start, $end - $start));
				$start = stripos($res, '<span class="text-price-number" data-price="');
				$end = stripos($res, '"', $start + strlen('<span class="text-price-number" data-price="'));
				$price = str_replace('<span class="text-price-number" data-price="', '', substr($res, $start, $end - $start));
				$start = stripos($content, '<div class="oul-detail-content" ref="oul-tab-01" id="paneSummary">');
				$end = stripos($content, '</div>', $start + 1);
				$detail = str_replace(["\t", "\r", "\n"], '', str_replace('<div class="oul-detail-content" ref="oul-tab-01" id="paneSummary">', '', substr($content, $start, $end - $start)));
				break;
			case '旋转拍卖':
				break;
				$content = Http::get($A,[],[
					CURLOPT_HTTPHEADER => [
						'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
						'Accept-Encoding:zh-CN,zh;q=0.9',
						'Cache-Control:max-age=0',
						'Sec-Ch-Ua:"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
						'Sec-Ch-Ua-Mobile:?0',
					
						'Sec-Fetch-Dest:document',
						'Sec-Fetch-Mode:navigate',
						'Sec-Fetch-Site:none',
						'Sec-Fetch-User:?1',
					],
					CURLOPT_ACCEPT_ENCODING => 'gzip, deflate, br',
					CURLOPT_USERAGENT=> 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
					CURLOPT_COOKIE => '_t2=zdKxn9EFI-; _gcl_au=1.1.576427545.1701422897; _fbp=fb.2.1701422899391.1626375633; WZRK_G=57af5aeab4e642c78bd2fcbd54a1280a; _csrf=cfZez3XzpuMsSalWAxOPnymi; _t=a%3DrL42NX5VdQ%26t%3D1702029201582; siv_2=f4dac13f-99dc-4aa3-87a3-62c9f15a5861; latra=1701993600000; _gid=GA1.3.694750516.1702029207; _gat=1; _gaclientid=2026387065.1701422897; _gasessionid=20231208|09117301; _gahitid=17:53:27; _dc_gtm_UA-32231169-26=1; _ga_BTYMG7D1RH=GS1.1.1702029207.2.0.1702029207.60.0.0; _ga=GA1.1.2026387065.1701422897; WZRK_S_8R9-448-845Z=%7B%22p%22%3A1%2C%22s%22%3A1702029207%2C%22t%22%3A1702029209%7D; cto_bundle=XwjSE19mYkNSb0xkZnlCZ0J2TEcyNERhQlVIT0FES050MjdIMjBjJTJCM1E1dnpuRHFRWTEwRVpzVGFjYVRVMnZNcXZrblF3JTJCSXFaZ3Q3Rkl4UWREVTRIQm55YndjanZ5OFJKNTVqN1IlMkZqbGlIT3BCM0YzbnM0OXNjaXVvZTM4NCUyQm9Fenp1VjYlMkJjR3dLa1RwNUVQdEpza3AzZGx0TjFEekJwNzVEc3VPYXZBdU13MExjJTNE; g_state='
				]);
				dd($content);
				
				$start = stripos($content, 'history.replaceState(null, null, "');
				$end = stripos($content, '"', $start + 35);
				$url = stripslashes(str_replace('history.replaceState(null, null, "', '', substr($content, $start, $end - $start)));
				$end = stripos($url, '?');
				$res = substr($url, 0, $end);
				$goods_pd = str_replace('/p/', '', $res);
				$content = Http::get('https://www.carousell.com.hk' . $url);
				dd($content);
				break;
			case '屈臣氏':
				break;
				$start = strrpos($A, '/');
				$goods_pd = 'BP_' . trim(strip_tags(substr($A, $start + 1)));
				$url = 'https://api.watsons.com.hk/api/v2/wtchk/products/search';
		
				$res = Http::get($url, ['fields' => 'FULL', 'query' => $goods_pd], [
					CURLOPT_HTTPHEADER => [
						'Accept'=>'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
					],
					CURLOPT_ACCEPT_ENCODING => 'gzip, deflate, br',
					CURLOPT_USERAGENT=> 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0',
					CURLOPT_COOKIE => '_abck=81B7E7B78487CCB663813EC881F4FED2~0~YAAQblcyuFrGUM+LAQAA/ynxSAsMVrQSVecKWproKCHEUq6Z1sZps1UTXcrq0lyY5JrnRXi2MpRAx8KCLvwjFmnxG9A03Q8IJGlYisWFBSU9JeIcBbWBU1/BfFz/Fdjy73G9Tkmkr09PDskFZ5nnJMkzo28xkvWPz854/Ze48P+Jk4v6yz35ZniJV/GsZhyEmaBrGNPPZQKwGOnAsmI69JCTHbi/t5swCi0D94wocqE2snzmeqLFIlJW9vqQK6eKH5Ln03fl1+HtNzqtcZhbZyN0uZLrgXKznzI2KEi05+y8N8qBhtyinROaq1mBcsqWxyIIE9UMnnQOHM33inP3V+oZYZEmXRmm8vbafVUNNTNaj9kQzr0VoQdtAblQnugV5bg/xJgwwklEVD4iNMvg4RTCEjrCpEzC+MCCamU=~-1~-1~-1; dtCookie=v_4_srv_32_sn_A7201C21189A1…w3NZYe+rRSUuTgIJKSOhsWgwYmJyTsCPqXrgzSYkhDbo~1; bm_sv=7701F712D5813A6F87984B269BDD5D8D~YAAQxoFtaCrrVuKLAQAA9zfxSBbQjC1vc4UP60K+rVmrwe7ZFxD+HHPIDhiKb+/aALZ0ScpuCXGPR7N4yYhbM59rCjzhZ1wLzy+w/HuvCYLsgJtDTX3li4q4PnysePylHgrQ1TiCHoV/6mqUOjqrVMlie9cbaZZZ26cAeXeaPb2RwUEJzbmwmaSzOuQB2zhlSdVvgKEKdrH2fzL2ZvMxglyPUMG/NcdEFlq4i3ssq0g59Emtdr5WgShIt/zADMEwpklNSjM=~1; PIM-SESSION-ID=nnqQAWc8bsBFw8hP; authorization=RK2D7U-O42UyAA_tZDXShDHlr_Y; token_type=guest; ROUTE=.api-6fc646bdcd-8mllw; _gcl_au=1.1.1121226656.1702030818'
				]);
				dd($res);
				$content = json_decode($res);
				if ($content) {
					$product = $content->products[0];
				} else {
					$content = simplexml_load_string($res);
					$content = json_encode($content);
					$content = json_decode($content);
					$product = $content->products;
				}
				$title = $product->name;
				$price = $product->price->value;
				$detail = $product->description;
				$images = $product->images;
				$arr = [];
				foreach ($images as $v) {
					$url =is_string($v)?$v:$v->url;
					$arr[] = 'https://api.watsons.com.hk'.$url  ;
				}
				$images = implode(',', $arr);
				break;
			case '莎莎':
				$url = get_redirect_url($A);
				$start = stripos($url, 'Index/');
				$end = stripos($url, '?', $start + 1);
				$res = substr($url, $start, $end - $start);
				$goods_pd = str_replace('Index/', '', $res);
				$start = stripos($url, 'shopId=');
				$end = stripos($url, '&', $start + 1);
				$res = substr($url, $start, $end - $start);
				$shopId = str_replace('shopId=', '', $res);
				$res = HTTP::get("https://www.sasa.com.hk/webapi/salepage/GetSalepageDataByIds?ids=$goods_pd&v=0&shopId=$shopId&lang=zh-HK");
				$res = json_decode($res);
				$images = 'https:' . $res->SalepageList[0]->PicUrl;
				$title = $res->SalepageList[0]->Title;
				$price = $res->SalepageList[0]->Price;
				$res = HTTP::get("https://webapi.91app.hk/webapi/SalePageV2/GetSalePageAdditionalInfo/$shopId/$goods_pd");
				$res = json_decode($res);
				$detail = $res->Data->MoreInfo->SaleProductDesc_Content;
				break;
			case 'MyDress':
				$url = get_redirect_url($A);
				$start = stripos($url, 'Index/');
				$end = stripos($url, '?', $start + 1);
				$res = substr($url, $start, $end - $start);
				$goods_pd = str_replace('Index/', '', $res);
				$start = stripos($url, 'shopId=');
				$end = stripos($url, '&', $start + 1);
				$res = substr($url, $start, $end - $start);
				$shopId = str_replace('shopId=', '', $res);
				$res = HTTP::get("https://www.mydress.com/webapi/salepage/GetSalepageDataByIds?ids=$goods_pd&v=0&shopId=$shopId&lang=zh-HK");
				$res = json_decode($res);
				$images = 'https:' . $res->SalepageList[0]->PicUrl;
				$title = $res->SalepageList[0]->Title;
				$price = $res->SalepageList[0]->Price;
				$res = HTTP::get("https://webapi.91app.hk/webapi/SalePageV2/GetSalePageAdditionalInfo/$shopId/$goods_pd");
				$res = json_decode($res);
				$detail = $res->Data->MoreInfo->SaleProductDesc_Content;
				break;
			case 'ZALORA':
				$A = str_replace('www', 'zh', $A);
				$start = strrpos($A, '-');
				$goods_pd = trim(strip_tags(substr($A, $start + 1)));
				$content = http_request($A);
				$start = stripos($content, '"application/json">');
				$end = stripos($content, '</script>', $start + 1);
				$res = substr($content, $start, $end - $start);
				$res = str_replace('"application/json">', '', $res);
				$res = json_decode($res);
				$goods = $res->props->pageProps->preloadedState->pdv->product;
				$price = $goods->Simples[0]->SpecialPrice;
				if (empty($price)){
					$price = $goods->Price;
				}
				$images = $goods->MediaCollection;
				$images = (array)$images;
				$images = array_column($images, 'Url');
				$images = implode(',', $images);
				$title = $goods->Name;
				$A = $goods->Url;
				$detail = $goods->ShortDescription;
				break;
			case '客路旅行':
				exit;
				$url = get_redirect_url($A);
				$start = stripos($url, 'activity/');
				$end = stripos($url, '/', $start + 10);
				if ($end===false){
					$end = stripos($url, '?', $start + 10);
				}
			
				$res = substr($url, $start, $end - $start);
				$goods_pd = str_replace('activity/', '', $res);
			
				$content = Http::get('https://www.klook.com/zh-CN/activity/77518-tokyo-mega-illumi/?utm_campaign=platform-share&utm_content=platform%3Dapp_pagespm%3DActivity_textversion%3D0_shareid%3D9abed5cb-7111-43f2-9ae6-37cc975291da&utm_medium=link-copy&utm_source=link-copy');
				$start = stripos($content, 'sale_price:"¥ ');
				$end = stripos($content, '"', $start + 15);
				$res = substr($content, $start, $end - $start);
				$price = str_replace('sale_price:"¥ ', '', $res);
				$start = stripos($content, '<span class="vam"');
				$start = stripos($content, '>', $start + 1);
				$end = stripos($content, '</span>', $start + 1);
				$title = trim(strip_tags(substr($content, $start + 1, $end - $start - 1)));
				$start = stripos($content, 'data-spm-virtual-item="__virtual" src="');
				$end = stripos($content, '"', $start + 50);
				$res = substr($content, $start, $end - $start);
				$images = str_replace('data-spm-virtual-item="__virtual" src="', '', $res);
				$start = stripos($content, '<div class="klk-markdown klk-markdown--highlight"');
				$start = stripos($content, '>', $start + 1);
				$end = stripos($content, '</div>', $start + 1);
				$detail = substr($content, $start + 1, $end - $start - 1);
				break;
			case '士多':
				$content = http_request($A);
				$start = stripos($content, '<script id="__NEXT_DATA__" type="application/json">');
				$end = stripos($content, '</script>', $start + 1);
				$json_info = trim(strip_tags(substr($content, $start, $end - $start)));
				$res = json_decode($json_info);
				$res = $res->props->pageProps->initialState->product->getProductByUrlKey;
				$goods_pd = $res->url_key;
				$price = $res->price->promotion_price;
				$title = $res->name;
				$detail = $res->description;
				$images = $res->images;
				$image_url = [];
				foreach ($images as $v) {
					$image_url[] = $v->normal;
				}
				$images = implode(',', $image_url);
				break;
			case 'PNS':
				exit;
				$start = strrpos($A, '/');
				$goods_pd = trim(strip_tags(substr($A, $start + 1)));
				$content = Http::get($A);
				dd($content);
				$start = stripos($content, '<script type="application/ld+json" class="structured-data">');
				$end = stripos($content, '</script>', $start + 1);
				$json_info = trim(strip_tags(substr($content, $start, $end - $start)));
				$res = json_decode($json_info);
				$res1 = $res[1];
				$price = $res1->offers->price;
				$title = $res1->name;
				$images = implode(',', $res1->image);
				$detail = $res[2]->description;
				break;
			case '香港宜家':
				$start = strrpos($A, '/');
				$goods_pd = trim(strip_tags(substr($A, $start + 1)));
				$content = Http::get($A);
				$start = stripos($content, 'var jsonld=');
				$end = stripos($content, ';', $start + 1);
				$json = trim(strip_tags(str_replace('var jsonld=', '', substr($content, $start, $end - $start))));
				$res = json_decode($json);
				$title = $res->name;
				$price = $res->offers->price;
				$images = implode(',', $res->image);
				$detail = $res->description;
				break;
			case 'iHerb':
				$res = str_contains($A, 'productId=');
				if ($res) {
					$start = stripos($A, 'productId=');
					$end = stripos($A, '&', $start + 1);
					$res = substr($A, $start, $end - $start);
					$goods_pd = str_replace('productId=', '', $res);
				} else {
					$start = strrpos($A, '/');
					$end = stripos($A, '?', $start + 1);
					$goods_pd = substr($A, $start + 1, $end - $start - 1);
				}
				$res = Http::get('https://catalog.app.iherb.com/recommendations/freqpurchasedtogether?productId=' . $goods_pd);
			
				$res = json_decode($res);
				$title = $res->originProduct->name;
				$price = $res->originProduct->discountedPriceAmount;
				$A = $res->originProduct->url;

//				$res = Http::get("https://cn.iherb.com/ugc/api/product/$goods_pd/review/images",[],[
//					CURLOPT_HTTPHEADER => [
//						'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
//						'Connection:keep-alive',
//						'Upgrade-Insecure-Requests:1',
//						'Sec-Fetch-Dest:document',
//						'Sec-Fetch-Mode:navigate',
//						'Sec-Fetch-Site:cross-site',
//						'TE:trailers'
//					],
//					CURLOPT_ACCEPT_ENCODING => 'gzip, deflate, br',
//					CURLOPT_USERAGENT=> "Popular browser\'s user-agent",
//				]); //图片
		
				
				break;
			default:
				$history = false;
		}
		
		$images = implode(',', array_unique(explode(',', $images)));
		return ['history' => $history, 'mall_id' => $mall_id, 'goods_pd' => $goods_pd, 'price' => $price, 'images' => $images, 'mall' => $name, 'title' => $title, 'detail' => $detail, 'url' => $A];
	}
}